//
//  GatherSegmentCell.m
//  YYTextTest
//
//  Created by macintosh on 16/9/12.
//  Copyright © 2016年 macintosh. All rights reserved.
//

#import "GatherSegmentCell.h"

NSString *GatherSegmentCellSegmentSelectedNotification = @"GatherSegmentCellSegmentSelectedNotification";

@interface GatherSegmentCell ()
@property (nonatomic, strong) NSMutableDictionary *segmentState;
@end

@implementation GatherSegmentCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return self;
}

- (void)setInfo:(GatherSegmentInfo *)info
{
    _info = info;
    
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:_info.items];;
    segment.tintColor = ColorRGB(0, 163, 223);
    [segment setWidth:50 forSegmentAtIndex:0];
    [segment setWidth:50 forSegmentAtIndex:1];
    segment.selectedSegmentIndex = _info.firstSelected ? 0 : 1;
    segment.enabled = _info.enabled;
    [segment addTarget:self action:@selector(selectSegment:) forControlEvents:UIControlEventValueChanged];
    self.accessoryView = segment;
    
    if (!_segmentState) {
        _segmentState = [NSMutableDictionary dictionary];
    }
    
    _segmentState[@"indexPath"] = _indexPath;
    
    self.textLabel.text = _info.title;
}

- (void)selectSegment:(UISegmentedControl *)segment
{
    _info.firstSelected = segment.selectedSegmentIndex == 0 ? YES : NO;
    _segmentState[@"firstSelected"] = @(_info.firstSelected);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:GatherSegmentCellSegmentSelectedNotification object:nil userInfo:_segmentState];
}

@end
